const storage = {}

// 默认缓存时间5分钟 毫秒
const DEFAULT_EXPIRES = 5 * 60 * 1000

function Structure(data,expires){
  return {
    data,
    // 过期时间
    expires
  }
}

function setCache(name,data,expires=DEFAULT_EXPIRES){
  storage[name] = Structure(data,expires===0?0:(expires||0)+Date.now())
}

function getCache(name){
  const now = Date.now()
  const data = storage[name]
  if(!data) return null;
  if(data.expires===0 || data.expires>now) return data.data;
  return null;
}

function getAll(){
  const all = {}
  const now = Date.now()
  Object.entries(storage).forEach(([key,ele])=>{
    if(ele.expires>now){
      all[key] = ele.data
    }
  })

  return all
}

function min2msec(min){
  return min * 60 * 1000
}

module.exports = {
  get:getCache,
  set:setCache,
  getAll,
  min2msec
}